package com.lmaos.basetools.files.scan.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.lmaos.basetools.files.scan.ScanFile;
import com.lmaos.basetools.files.scan.ScanFileExecute;
import com.lmaos.basetools.files.scan.ScanFileUtils;
import com.lmaos.basetools.files.scan.SuffixScanFileParse;

public class BasicScanFileExecute implements ScanFileExecute{
	protected Map<String, SuffixScanFileParse> suffixScanFileParses = new HashMap<String, SuffixScanFileParse>();
	@Override
	public void addSuffixScanFileParse(String suffix, SuffixScanFileParse scanFileParse) {
		suffixScanFileParses.put(suffix, scanFileParse);
	}
	
	@Override
	public List<ScanFile> execScan(String rootPath) {
		rootPath = ScanFileUtils.getFileString(rootPath);
		File rootFile = new File(rootPath);
		if(rootFile.isFile()){
			return scanIsFile(rootPath, rootFile);
		}
		List<ScanFile> scanFiles = new ArrayList<ScanFile>();
		List<File> dirFiles = new ArrayList<File>();
		dirFiles.add(rootFile);
		for (int i = 0; i < dirFiles.size(); i++) {
			File dirFile = dirFiles.get(i);
			File[] subFiles = dirFile.listFiles();
			for (File subFile : subFiles) {
				if(subFile.isDirectory()){
					dirFiles.add(subFile);
				}else{
					List<ScanFile> scanSubFiles = scanIsFile(rootPath, subFile);
					if(scanSubFiles!=null&&scanSubFiles.size()>0){
						scanFiles.addAll(scanSubFiles);
					}
				}
			}
		}
		
		return scanFiles;
	}
	// 对文件扫描呵呵
	protected List<ScanFile> scanIsFile(String rootPath,File file){
		String absolutePath = file.getAbsolutePath();
		String suffixName = ScanFileUtils.getSuffixString(absolutePath);
		SuffixScanFileParse suffixScanFileParse = suffixScanFileParses.get(suffixName);
		if(suffixScanFileParse!=null){
			// 通过后缀进行扫描
			return suffixScanFileParse.parseScanFiles(rootPath,absolutePath, suffixName);
		}else{
			String filePath = absolutePath.substring(rootPath.length());
			return Arrays.asList(new ScanFile(rootPath, filePath, absolutePath));
		}
	}

	@Override
	public SuffixScanFileParse getSuffixScanFileParse(String suffix) {
		// TODO Auto-generated method stub
		return suffixScanFileParses.get(suffix);
	}

}
